package com.it.smartoldb.service.impl;

import com.it.smartoldb.dto.LoginRequest;
import com.it.smartoldb.dto.LoginResponse;
import com.it.smartoldb.entity.User;
import com.it.smartoldb.repository.UserRepository;
import com.it.smartoldb.service.AuthService;
import com.it.smartoldb.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 认证服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {

    private final UserRepository userRepository;
    private final JwtUtil jwtUtil;

    @Override
    public LoginResponse login(LoginRequest request) {
        log.info("用户登录: {}", request.getUsername());
        log.info("请求密码: {}", request.getPassword());
        
        // 查找用户
        User user = userRepository.findByUsername(request.getUsername())
                .orElseThrow(() -> {
                    log.error("用户不存在: {}", request.getUsername());
                    return new RuntimeException("用户名或密码错误");
                });
        
        log.info("找到用户: {}, 角色: {}, 状态: {}", user.getUsername(), user.getRole(), user.getStatus());
        log.info("数据库密码: {}", user.getPassword());
        
        // 验证密码（明文比较）
        boolean passwordMatches = request.getPassword().equals(user.getPassword());
        log.info("密码匹配结果: {}", passwordMatches);
        
        if (!passwordMatches) {
            log.error("密码验证失败");
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }
        
        // 生成JWT令牌
        String token = jwtUtil.generateToken(user.getUsername(), user.getRole(), user.getId());
        
        // 构建响应
        LoginResponse response = new LoginResponse();
        response.setToken(token);
        response.setUsername(user.getUsername());
        response.setRole(user.getRole());
        response.setUserId(user.getId());
        
        log.info("用户登录成功: {}", user.getUsername());
        return response;
    }

    @Override
    public void logout() {
        // JWT是无状态的，这里可以实现token黑名单或其他登出逻辑
        log.info("用户退出登录");
    }

    @Override
    public LoginResponse getCurrentUser() {
        // 这里应该从SecurityContext获取当前用户信息
        // 暂时返回空实现
        return new LoginResponse();
    }
} 